import Vue from 'vue'
import VueI18n from 'vue-i18n'

import zh from './locales/zh'
import kr from './locales/kr'
import en from './locales/en'
import vn from './locales/vn'

Vue.use(VueI18n)

const LOCALE_KEY = 'localeLanguage'


let DEFAULT_LANG = 'zh';
let lang = navigator.language || navigator.userLanguage || navigator.browserLanguage;
if (lang.substr(0, 3) === "zh-"){
	DEFAULT_LANG = 'zh'
}
if (lang.substr(0, 2) === "ko"){
	DEFAULT_LANG = 'kr'
}
if (lang.substr(0, 2) === "en"){
	DEFAULT_LANG = 'en'
}
if (lang.substr(0, 2) === "vi"){
	DEFAULT_LANG = 'vn'
}

const locales = {
	zh,
	kr,
	en,
	vn
}

const i18n = new VueI18n({
	locale: DEFAULT_LANG,
	messages: locales,
})

export const getCookie = name => {
    var arr, reg = new RegExp("(^| )" + name + "=([^;]*)(;|$)");
    if (arr = document.cookie.match(reg)){
        return unescape(arr[2]);
    } else {
        return null;
    }
}

export const setup = lang => {
	if (lang === undefined || lang === null) {
		lang = getCookie('lang') || window.localStorage.getItem(LOCALE_KEY)
	}
	if (locales[lang] === undefined) {
		lang = DEFAULT_LANG
	}
	window.localStorage.setItem(LOCALE_KEY, lang)

	Object.keys(locales).forEach(lang => {
		document.body.classList.remove(`lang-${lang}`)
	})
	document.body.classList.add(`lang-${lang}`)
	document.body.setAttribute('lang', lang)

	Vue.config.lang = lang
	i18n.locale = lang
}

setup()

export default i18n
